<template>
  <div>
    <a-row style="padding: 20px 10px 0px 10px">
      <a-col :flex="1">
        <a-form
          :model="formModel"
          :label-col-props="{ span: 8 }"
          :wrapper-col-props="{ span: 16 }"
          label-align="left"
        >
          <a-row>
            <a-form-item field="keywords" label="关键词">
              <a-input-search
                v-model="formModel.keywords"
                allow-clear
                placeholder="请输入关键词"
                search-button
                @search="fetchData"
              />
            </a-form-item>
          </a-row>
        </a-form>
      </a-col>
    </a-row>
    <a-table
      row-key="id"
      :scroll="true"
      :loading="loading"
      :data="renderData"
      :bordered="false"
      :pagination="false"
      show-empty-tree
      :row-class="rowClass"
      @row-click="rowClick"
    >
      <template #columns>
        <a-table-column title="科目编码" data-index="code" />
        <a-table-column title="科目名称" data-index="standardText" />
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
  import useLoading from '@/hooks/loading';
  import { defineEmits, ref } from 'vue';
  import { accountSubjectAll } from '@/api/invoice';

  const { loading, setLoading } = useLoading();
  const formModel = ref({
    keywords: '',
  });
  const renderData = ref([]);
  const selectedRow = ref<string | null>(null);
  const emit = defineEmits(['change']);
  const rowClick = (record: any) => {
    selectedRow.value = record.id;
    emit('change', record.code);
  };
  const rowClass = (record: any) => {
    return record.id === selectedRow.value ? 'select-row' : '';
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await accountSubjectAll(formModel.value.keywords);
      renderData.value = data;
      if (renderData.value) {
        rowClick(renderData.value[0]);
      }
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  fetchData();
</script>

<style scoped lang="less">
  /* 自定义行样式 */
  :deep(.select-row) td {
    background-color: #e6e6ec !important; /* 错误行红色背景 */
  }
</style>
